//
//  HWLoginModule.m
//  HWLoginModule
//
//  Created by yehuawei on 2018/11/16.
//  Copyright © 2018 postop. All rights reserved.
//

#import "HWLoginModule.h"

#define key_loggedInAccount @"key_loggedInAccount"

#define key_loggedInPassword @"key_loggedInPassword"

#define key_islogin @"key_islogin"

#define keyPath_isLogin @"isLogin"

@implementation HWLoginModule

//全局变量
static id _instance = nil;
//单例方法
+(instancetype)sharedLoginModule{
    
    return [[self alloc] init];
}
////alloc会调用allocWithZone:
+(instancetype)allocWithZone:(struct _NSZone *)zone{
    //只进行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}
//初始化方法
- (instancetype)init{
    // 只进行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super init];
        /*
         判断是否登录
         */
        // 取出上一次是否登录成功的标示, 以及密码是否存在
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        BOOL isLogin = [defaults boolForKey:key_islogin];
        
        [_instance setValue:@(isLogin) forKey:keyPath_isLogin];
    });
    
    return _instance;
}

-(void)loggedIn
{
    [self loggedInWithAccount:nil];
}

-(void)loggedInWithAccount:(NSString *)account
{
    [self loggedInWithAccount:account password:nil];
}

-(void)loggedInWithAccount:(NSString *)account password:(NSString *)password
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    if (account) {
        [defaults setObject:account forKey:key_loggedInAccount];
    }
    
    if (password) {
        [defaults setObject:password forKey:key_loggedInPassword];
    }
    
    [defaults setBool:YES forKey:key_islogin];
    
    [defaults synchronize];
    
    [self setValue:@(YES) forKey:keyPath_isLogin];
    
    
    
}

-(void)logout
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:key_loggedInPassword];
    [defaults setBool:NO forKey:key_islogin];
    [defaults synchronize];
    [self setValue:@(NO) forKey:keyPath_isLogin];
}

//copy在底层 会调用copyWithZone:
- (id)copyWithZone:(NSZone *)zone{
    return  _instance;
}

- (id)mutableCopyWithZone:(NSZone *)zone{
    return _instance;
}

-(NSString *)lastAccount
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *accountStr = [defaults objectForKey:key_loggedInAccount];
    return accountStr;
}

-(NSString *)lastPassword
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *passwordStr = [defaults objectForKey:key_loggedInPassword];
    return passwordStr;
}

@end
